package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.client.methods.HttpGet;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.exception.self.UnableParseRouteTypeException;
import com.foreveross.crawl.domain.airfreight.AbstractPlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.single.SinglePlaneInfoEntity;
import com.foreveross.crawl.exception.FlightInfoNotFoundException;
import com.foreveross.taskservice.common.bean.TaskModel;

/**
 * 淘宝的另一个版本，全程采用httpclient，试验下成功率
 * @author guokenye
 * 
 */
public class TaobaoAdapter extends AbstractAdapter {
	public static final Long TaoBao_GradChannel = 4L;

	public TaobaoAdapter(TaskModel taskQueue) {
		super(taskQueue);
	}

	@Override
	public String getUrl() throws Exception {
		return null;
	}


	@Override
	public Object fetch(String url) throws Exception {
		switch (super.getRouteType()) {
		case DOMESTIC_ONEWAYTRIP:
			return fetchDomesticOneWay();
		default:
			throw new UnableParseRouteTypeException(taskQueue, getRouteType()
					.getName());
		}
	}

	private Object fetchDomesticOneWay() throws Exception {
		Map<String, String> p2 = new HashMap<String, String>();
		String jsonStr;
		HttpGet g = null;
		try {
			g = new HttpGet();
			super.excuteRequest(super.getBaseGet("http://trip.taobao.com/jipiao/", null));
			p2.put("depCity",taskQueue.getFromCity());
			p2.put("arrCity",taskQueue.getToCity());
			p2.put("depCityName", taskQueue.getFromCityName());
			p2.put("arrCityName", taskQueue.getToCityName());
			p2.put("depDate", this.taskQueue.getFlightDate());
			p2.put("tripType", "0");
			p2.put("agentIds", "");
			p2.put("supplyItinerary", "");
			p2.put("autoBook", "");
			p2.put("cabinClass", "");
			p2.put("searchSource", "99");
			p2.put("searchBy", "1280");
			p2.put("passengerNum", "");
			p2.put("callback", "");
			p2.put("ua", "");
			p2.put("type", "");
			g.setURI(new URI(this.getBaseGetUrl(
					"http://s.jipiao.trip.taobao.com/searchow/search.htm", p2)));
			jsonStr = super.excuteRequest(g);
			super.appendPageContents(jsonStr);
		} finally {
			p2 = null;
			g = null;
		}
		return jsonStr;
	}


	@SuppressWarnings("deprecation")
	@Override
	public boolean validateFetch(Object obj) throws Exception {
		if (obj == null) {
			throw new Exception("淘宝数据为空");
		}
		switch (super.getRouteType()) {
		case DOMESTIC_ONEWAYTRIP:
			obj = URLDecoder.decode(obj.toString()).replaceAll("\\s", "");

			if (obj.toString().matches(".*很抱歉，您查询的.*没有航线.*")
					|| obj.toString().matches(".*当天无航班.*")
					|| obj.toString().matches(".*当前已无可售航班.*")
					|| obj.toString().matches(".*无航线.*")) {
				throw new FlightInfoNotFoundException();
			}
			if (!obj.toString().matches(".*\"error\":0.*")) {
				throw new Exception("淘宝获得的数据错误");
			}
			if (obj.toString().matches(".*验证码.*")) {
				throw new Exception("淘宝出现尼玛的验证码");
			}
			break;
		default:
			throw new UnableParseRouteTypeException("淘宝", super.getRouteType()
					.getName());
		}
		return true;
	}

	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		List<AbstractPlaneInfoEntity> entitys = new ArrayList<AbstractPlaneInfoEntity>();
		String jsonStr;
		JSONObject j;
		JSONObject air;
		JSONArray flights;
		JSONObject f;
		SinglePlaneInfoEntity singleEntity;
		try {
			jsonStr = fetchObject.toString().replaceAll("^[^\\(]*\\(", "").replaceAll(";$", "").replaceAll("\\)$", "");
			j = JSONObject.fromObject(jsonStr);
			// 得到aircodeNameMap
			air = j.getJSONObject("data").getJSONObject("aircodeNameMap");
			flights = j.getJSONObject("data").getJSONArray("flight");
			for (int i = 0; i < flights.size(); i++) {
				f = flights.getJSONObject(i);
				// 目前json insurePrice 就是显示的最低价
				double taxesPrice = f.getDouble("oilPrice")+ f.getDouble("buildPrice");
				JSONObject cj = f.getJSONObject("cabin");
				singleEntity = PlaneInfoEntityBuilder.buildPlaneInfo(
						this.taskQueue, f.getString("airlineCode"), air
								.getString(f.getString("airlineCode")), air
								.getString(f.getString("airlineCode")), null,null, f
								.getString("flightNo"), null, cj.getString("agentId"), null, f
								.getString("flightType"),null, null,null,null, SinglePlaneInfoEntity.class);
				singleEntity.setFromCity(f.getString("depAirport"));
				singleEntity.setToCity(f.getString("arrAirport"));
				singleEntity.setStartTime(DateUtils.parseDate(f.getString("depTime"), "yyyy-MM-dd HH:mm"));
				singleEntity.setEndTime(DateUtils.parseDate(f.getString("arrTime"), "yyyy-MM-dd HH:mm"));
				//没有获得所有价格，这里不再最高价格及其税费
				singleEntity.setTotalHighestPrice(null);
				singleEntity.setTotalHighestTaxesPrice(null);
				singleEntity.setSumHighestPrice(null);
				singleEntity.setTotalLowestPrice(cj.getDouble("insurePrice"));
				singleEntity.setTotalLowestTaxesPrice(taxesPrice);
				singleEntity.setSumLowestPrice(singleEntity.getTotalLowestPrice()+ singleEntity.getTotalLowestTaxesPrice());
				
				logger.info(String.format("淘宝 [%s][%s][%s] 航班[%s] 最高价[%s] 最低价[%s]",this.taskQueue.getFromCity(),this.taskQueue.getToCity(),
						this.taskQueue.getFlightDate(),singleEntity.getFlightNo(),	singleEntity.getTotalHighestPrice(),singleEntity.getTotalLowestPrice()));
				entitys.add(singleEntity);
			}
		} finally {
			jsonStr = null;
			j = null;
			air = null;
			flights = null;
			f = null;
			fetchObject = null;
		}
		return Arrays.asList(entitys.toArray());
	}

}
